﻿using ch03.binary.module;

namespace ch03.binary.wasm_reader
{
    public partial struct WasmReader
    {
        // import sec
        private Import[] ReadImportSec()
        {
            var vec = new Import[ReadVarU32()];
            for (var i = 0; i < vec.Length; i++)
            {
                vec[i] = ReadImport();
            }

            return vec;
        }

        private Import ReadImport()
        {
            return new Import
            {
                Module = ReadName(),
                Name = ReadName(),
                Desc = ReadImportDesc(),
            };
        }

        private ImportDesc ReadImportDesc()
        {
            var desc = new ImportDesc {Tag = ReadByte()};
            switch (desc.Tag)
            {
                case ConstData.ImportTagFunc:
                    desc.FuncType = ReadVarU32();
                    break;
                case ConstData.ImportTagTable:
                    desc.Table = ReadTableType();
                    break;
                case ConstData.ImportTagMem:
                    desc.Mem = ReadLimits();
                    break;
                case ConstData.ImportTagGlobal:
                    desc.Global = ReadGlobalType();
                    break;
                default:
                    Panic.Run("invalid import desc tag: %d", desc.Tag);
                    break;
            }

            return desc;
        }
    }
}